﻿using System.Collections.Generic;
using Base.Runtime;
using UnityEngine;
using UnityEngine.UI;
using Object = System.Object;

namespace UIModule
{
    public abstract class WindowBase : XObject
    {
        public LinkedListNode<WindowBase> Node;
        public WindowOpenData Data;
        public GameObject WindowGameObject { get; private set; }
        public DataInjection DataInjection { get; private set; }
        public Canvas Canvas { get; private set; }
        public GraphicRaycaster GraphicRaycaster  { get; private set; }

        private UIStackLayer _layer;
        public void Init(Object userData)
        {
            OnInit(userData);
        }
        
        #region Interal
     
        #endregion
        public void SetDepth(int depth)
        {
            bool changed = Canvas.sortingOrder != depth;
            Canvas.sortingOrder = depth;
            if (changed)
            {
                OnDepthChanged(depth);
            }
        }
        
        public void InitComponent(UIStackLayer layer, GameObject instance)
        {
            _layer = layer;
            WindowGameObject = instance;
            DataInjection = instance.GetComponent<DataInjection>();
            Canvas = WindowGameObject.GetComponent<Canvas>();
            Canvas.overrideSorting = true;
            GraphicRaycaster = WindowGameObject.GetComponent<GraphicRaycaster>();
            OnInitComponent(DataInjection);
        }
        
        public void BeforeOpen()
        {
            Debug.Log("BeforeOpen");
            OnBeforeOpen();
        }

        public void Open()
        {
            GraphicRaycaster.enabled = true;
            OnOpen();
            Debug.Log("Open");
        }

        public void Update()
        {
            OnUpdate();
        }

        public void Cover()
        {
            GraphicRaycaster.enabled = false;
            OnCover();
            Debug.Log("Cover");
        }

        public void Reveal()
        {
            GraphicRaycaster.enabled = true;
            OnReveal();
            Debug.Log("Reveal");
        }

        protected void CloseWindow()
        {
            Debug.Log("CloseWindow");
            _layer.CloseWindow(this);
        }

        public void Close()
        {
            OnClose();
        }
        
        protected abstract void OnInit(object userData);
        protected abstract void OnInitComponent(DataInjection dataInjection);
        protected abstract void OnOpen();
        protected virtual void OnBeforeOpen(){}
        protected virtual void OnCover(){}
        protected virtual void OnReveal(){}
        protected virtual void OnUpdate(){}
        protected virtual void OnClose(){}
        protected virtual void OnDepthChanged(int depth){}
        protected override void OnDispose()
        {
            
        }
    }
}